import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/controller/MyPageState.dart';
import 'package:flutter_juwo/ui/controller/NetUtils.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/custom/NotLoginPage.dart';
import 'package:flutter_juwo/ui/custom/judje_dialog.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/custom/platform_dialog.dart';
import 'package:flutter_juwo/ui/model/base_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/progress_view.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';

import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';

import 'model/account_list_entity.dart';
import 'model/platform_entity.dart';

class AccountList extends StatefulWidget {
  String isFromTask="0";


  AccountList(this.isFromTask);

  @override
  _AccountListState createState() => _AccountListState();
}

class _AccountListState extends State<AccountList>
    with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  AccountListEntity entity = null;
  MyPageState ps = MyPageState.LOADING;

  EasyRefreshController _easyRefreshController = EasyRefreshController();
  int _selectValue = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.init();

    if(widget.isFromTask=="1"){
      var widgetsBinding = WidgetsBinding.instance;
      widgetsBinding.addPostFrameCallback((callback) {
        //会在Build完成时 回调 nice
        showMyDialog();
        getPlatFormInfor();
      });
    }


  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: this.appBar(context, "我的电商账号"),
      body: Column(
        children: <Widget>[
          UiUtils.divider(),
          Expanded(
            flex: 1,
            child: getContent(),
          )
        ],
      ),
    );
  }

  getContent() {
    if (SpUtil.getString(SpKeys.userToken).isEmpty) {
      ps = MyPageState.NOT_LOGIN;
    }

    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }
    if (ps == MyPageState.NOT_LOGIN) {
      return NotLoginPage();
    }

    if (ps == MyPageState.NOT_DATA) {
      return NoData(this.getData);
    }

    if (ps == MyPageState.HAVE_DATA) {
      if (null == entity) {
        init();
        return LoadingPage();
      }
      return EasyRefresh.custom(
        controller: _easyRefreshController,
        enableControlFinishRefresh: true,
        header: BallPulseHeader(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 1), () {
            this.getData();
          });
        },
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return this.getItem(entity.data[index]);
              },
              childCount: entity.data.length,
            ),
          ),
        ],
      );
    }

    return NoData(this.getData);
  }

  Future getData() async {
    DioManager.getInstance().get(Api.USER_GETACCOUNTLIST, null, (json) {
      AccountListEntity data = AccountListEntity.fromJson(json);
      if (data.code == Api.SUCCESS_CODE) {
        ///1.判断有没有获取到数据
        if (null == data.data || data.data.length <= 0) {
          this.noData();
          return;
        }

        ///2.判断本来有没有数据
        if (null == entity) {
          entity = data;
          this.haveData();
          return;
        }
        entity = data;
        this.haveData();
        if(mounted){
          setState(() {});
          _easyRefreshController.finishRefresh();
        }

      }
    }, (errMsg) {
      ToastUtil.showShortErrToast(errMsg);
      _easyRefreshController.finishRefresh();
      ps = MyPageState.NOT_DATA;
      setState(() {});
    });
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  getItem(AccountListData data) {
    List<Widget> listOpert = [];
    for (int i = 0; i < data.btns.length; i++) {
      listOpert.add(getOperItem(data.btns[i], data.item.platId, data.item.id));
    }
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(10)),
      padding: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), ScreenUtil().setWidth(30), ScreenUtil().setWidth(20)),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              //图片
              Container(
                child: CachedNetworkImage(
                  width: ScreenUtil().setWidth(40),
                  height: ScreenUtil().setWidth(40),
                  fit: BoxFit.contain,
                  imageUrl: data.item.pic,
                  placeholder: (context, url) => new ProgressView(
                    width: 40,
                  ),
                  errorWidget: (context, url, error) => new Icon(
                    Icons.error,
                    color: Colors.redAccent,
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                child: Text(
                  data.item.account,
                  style: TextStyles.custom(
                      30, Colours.appC1, Font.PingFangMedium),
                ),
              ),
              Expanded(
                flex: 1,
                child: Container(
                  alignment: Alignment.centerLeft,
                  margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
                  child: Text(
                    data.item.statusCn,
                    style: TextStyles.custom(
                        26,
                        data.item.status == "1" ? Colors.green : Colours.appC10,
                        Font.PingFangMedium),
                  ),
                ),
              ),
              Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: listOpert,
                ),
              )
            ],
          ),
          data.item.limit.isEmpty?Container(): Container(
            margin: EdgeInsets.only(top: ScreenUtil().setWidth(20)),
            alignment: Alignment.centerLeft,
            child: Text(
              data.item.limit,
              style: TextStyles.custom(
                  26, Colours.appC16, Font.PingFangMedium),
            ),
          )
        ],
      ),
    );
  }

  void init() {
    bool isLogin = NetUtils.isLogin();
    if (isLogin) {
      ///获取数据
      this.getData();
    } else {
      ps = MyPageState.NOT_LOGIN;
    }
  }

  ///更新、删除
  Widget getOperItem(AccountListDataBtn btn, String platId, String id) {
    String c = btn.color.replaceAll("#", "");
    int color = int.parse("0xFF${c}");
    return GestureDetector(
      onTap: () {
        if (btn.action == "update") {
          ///跳转到更新
          ///跳转到相应的平台
          NavigatorUtils.pushResult(
              context, "${Routes.initPlatAccount}?platId=$platId&&id=$id",
              (result) {
            if (result) {
              _easyRefreshController.callRefresh();
            }
          });
        } else if (btn.action == "delete") {
          showDeleteDialog(id);
        }
      },
      child: Container(
        margin: EdgeInsets.only(left: ScreenUtil().setWidth(26)),
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(10),
            ScreenUtil().setWidth(2),
            ScreenUtil().setWidth(10),
            ScreenUtil().setWidth(2)),
        child: Text(
          btn.text,
          style:
              TextStyles.custom(28, Color(color), Font.PingFangMedium),
        ),
      ),
    );
  }

  appBar(BuildContext context, String title) {
    return AppBar(
      brightness: Brightness.light,
      backgroundColor: Colours.white,
      title: Text(
        '$title',
        style: TextStyle(
            fontSize: ScreenUtil().setSp(34),
            fontFamily: Font.PingFangBlod,
            color: Colours.appC1),
      ),
      centerTitle: true,
      elevation: 0.0,
      leading: InkWell(
          highlightColor: Color(0xFFB3E5FC),
          onTap: () {
            Navigator.pop(context);
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(12.0, 0.0, 12.0, 0.0),
            child: Image.asset(
              Utils.getImgPath('return_left'),
              width: 18.0,
              height: 20.0,
            ),
          )),
      actions: <Widget>[
        Container(
          alignment: Alignment.center,
          padding: EdgeInsets.all(ScreenUtil().setWidth(30)),
          child: GestureDetector(
            onTap: () {
              ///获取可添加账号的信息
              showMyDialog();
              getPlatFormInfor();
            },
            child: Text(
              "新增",
              style: TextStyles.custom(
                  26, Colours.appC16, Font.PingFangMedium),
            ),
          ),
        )
      ],
    );
  }

  void getPlatFormInfor() {
    DioManager.getInstance().get(Api.USER_GETPLATLIST, null, (json) {
      print(json);

      PlatformEntity entity = PlatformEntity.fromJson(json);
      if (null == entity) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        NavigatorUtils.goBack(context);
        return;
      }

      if (entity.code != 200) {
        ToastUtil.showShortErrToast(entity.message);
        NavigatorUtils.goBack(context);
        return;
      }
      NavigatorUtils.goBack(context);

      ///显示Dialog
      showElasticDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return PlatformDialog(
              value: _selectValue,
              platformEntity: entity,
              onPressed: (value) {
                setState(() {
                  _selectValue = value;
                });

                ///跳转到相应的平台
                NavigatorUtils.pushResult(
                    context,
                    "${Routes.initPlatAccount}?platId=${entity.data[value].id}&&id="
                    "", (result) {
                  if (result) {
                    _easyRefreshController.callRefresh();
                  }
                });
              },
            );
          });
    }, (err) {
      ToastUtil.showShortErrToast(err);
      NavigatorUtils.goBack(context);
    });
  }

  void showMyDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return LoadingDialog(
            text: "查询可添加平台",
          );
        });
  }

  void showDeleteDialog(String id) {
    showElasticDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return JudjeDialog(
            title: "确定删除",
            value: "确定后将清除此账号数据!",
            onPressed: () {
              Navigator.pop(context);
              FormData params = FormData.from({"id": id});
              DioManager.getInstance().post(Api.USER_DELUSERACCOUNT, params,
                  (json) {
                BaseEntity entity = BaseEntity.fromJson(json);
                if (null == entity) {
                  ToastUtil.showShortErrToast("删除失败请稍后再试！");
                  return;
                }
                if (entity.code != 200) {
                  ToastUtil.showShortErrToast(entity.message);
                  return;
                }
                ToastUtil.showShortErrToast("删除成功");
                _easyRefreshController.callRefresh();
              }, (err) {});
            },
          );
        });
  }
}
